package com.atguigu.singleton;

/**
 * 典型的 双重检查。
 */
public class SingletonTest06 {
    public static void main(String[] args) {
        Singleton06 instance1 = Singleton06.getInstance();
        Singleton06 instance2 = Singleton06.getInstance();

        System.out.println(instance1 == instance2);
        System.out.println(instance1.hashCode() + "\t" + instance2.hashCode());
    }

}


class Singleton06 {
    // 构造函数私有化
    private Singleton06() {
    }
    // volatile保证线程的可见性， 效果更好。
    private static volatile Singleton06 instance;

    // 双重检查
    public static Singleton06 getInstance() {
        if (instance == null) {
            synchronized (Singleton06.class) {
                if (instance == null)
                    instance = new Singleton06();
            }
        }
        return instance;
    }

}